//
//  InsuranceDetailInfoViewController.m
//  CPICApp
//
//  Created by sinosoft on 13-3-19.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "InsuranceDetailInfoViewController.h"
#import "Appdelegate.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "ASIHTTPRequest.h"
#import "Config.h"
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuthObject.h>
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"
#import "RCCaculateIntegral.h"

@interface InsuranceDetailInfoViewController ()

@end

@implementation InsuranceDetailInfoViewController
@synthesize strInsuranceID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"保险知识详情");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"保险知识详情");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"保险知识详情");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    NSInteger viewHeight;
    if (IS_IPHONE_5) {
        viewHeight=420;
    }
    else
    {
        viewHeight=340;
    }
    CGRect imageframe=CGRectMake(0, 44, self.view.frame.size.width, viewHeight);
    imageScrollView=[[UIScrollView alloc]initWithFrame:imageframe];
    
    imageContent=[[UIImageView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 340)];
    [imageContent setImage:[UIImage imageNamed:@"company.png"]];
    //[self.view addSubview:imageContent];
    [imageScrollView addSubview:imageContent];
    [self.view addSubview:imageScrollView];
    
    txwContent=[[UITextView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, viewHeight)];
    txwContent.enablesReturnKeyAutomatically=YES;
    txwContent.editable=NO;
    [self.view addSubview:txwContent];
    
    UIButton *btnSharedSina=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnSharedSina setTitle:@"分享到新浪微博" forState:UIControlStateNormal];
    [btnSharedSina addTarget:self action:@selector(shareSina) forControlEvents:UIControlEventTouchDown];
    [btnSharedSina setBackgroundImage:[UIImage imageNamed:@"userBind.png"] forState:UIControlStateNormal];
    btnSharedSina.frame=CGRectMake(15, viewHeight+60, 130, 30);
    [self.view addSubview:btnSharedSina];
    
    UIButton *btnSharedQQ=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnSharedQQ setTitle:@"分享到腾讯微博" forState:UIControlStateNormal];
    [btnSharedQQ addTarget:self action:@selector(shareQQ) forControlEvents:UIControlEventTouchDown];
    [btnSharedQQ setBackgroundImage:[UIImage imageNamed:@"userBind.png"] forState:UIControlStateNormal];
    btnSharedQQ.frame=CGRectMake(175, viewHeight+60, 130, 30);
    [self.view addSubview:btnSharedQQ];
    
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
//NSString *appid = @"100389997";
    NSString *appid = @"222222";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
    [self setRequest];
}

-(void)setRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=50302";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setObject:strInsuranceID forKey:@"insuranceID"];
    [dicRequest setObject:@"admin22" forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"50302" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        //[NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    };
    
    
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    //arrData=[dictAppointmentList objectForKey:@"data"];
    NSString *strImgOrInfoTag=[[NSString alloc]initWithFormat:@"%@",[dictResponse valueForKey:@"imgOrInfoTag"]];
    strInsuranceTitle=[[NSString alloc]initWithFormat:@"%@",[dictResponse valueForKey:@"insuranceTitle"]];
    if ([strImgOrInfoTag isEqualToString:@"1"])//图片
    {
        isImage=YES;
        isContent=NO;
        txwContent.hidden=YES;
        ImgUrl=[dictResponse valueForKey:@"insuranceImgcontentUrl"];
//        ImgUrl=[NSString stringWithFormat:@"%@%@",Image_Url,ImgUrl];
        ImgUrl=[[NSString alloc]initWithFormat:@"%@%@",Image_Url,ImgUrl];
        ImgUrl = [ImgUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
        NSURL *urlCompanyImg=[NSURL URLWithString:ImgUrl];
        [imageContent setImageWithURL:urlCompanyImg success:^(UIImage *image) {
            imageDown=imageContent.image;
            NSLog(@"image height:%f",imageDown.size.height);
            NSLog(@"image width:%f",imageDown.size.width);
            imageHeght=imageDown.size.height;
            imageWidth=imageDown.size.width;
            imageContent.frame=CGRectMake(0, 0, imageWidth, imageHeght);
            
            imageScrollView.contentSize=CGSizeMake(imageDown.size.width, imageDown.size.height);
            imageScrollView.scrollEnabled=YES;
        } failure:^(NSError *error) {
        }];
    }
    else if([strImgOrInfoTag isEqualToString:@"0"])//文字信息
    {
        isContent=YES;
        isImage=NO;
        imageContent.hidden=YES;
        txwContent.text=[dictResponse valueForKey:@"insuranceInfo"];
    }
    
//    NSString *serviceid =@"50302";
//    NSString *servicename =@"保险知识详情";
//    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
//    [ifserviceevaluation setIfServiceEvaluationRequest];
//    [ifserviceevaluation setHidden:YES];
//    [self.view addSubview:ifserviceevaluation];
//    [ifserviceevaluation release];

}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

static int post_image_status_times = 0;
static int post_status_times = 0;
-(void)shareSina
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=1;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    NSLog(@"%@", [keyWindow subviews]);
    
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isAuthValid]) {
        //[self justShowMessage:@"你已经授权新浪微博" title:@"提示"];
        if (isImage==YES && isContent==NO) {
            if (!postImageStatusText)
            {
                post_image_status_times ++;
                [postImageStatusText release], postImageStatusText = nil;
                //postImageStatusText = [[NSString alloc] initWithFormat:@"CPICApp image status : %i %@", post_image_status_times, [NSDate date]];
                postImageStatusText=[[NSString alloc] initWithFormat:@"【保险知识分享】%@,欢迎使用《车E服》(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml)",strInsuranceTitle];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postImageStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 1;
            [alertView show];
            [alertView release];
        }
        else if(isImage==NO && isContent==YES)
        {
            if (!postStatusText)
            {
                post_status_times ++;
                [postStatusText release], postStatusText = nil;
//                postStatusText = [[NSString alloc] initWithFormat:@"CPICApp text status : %i %@%@", post_status_times, [NSDate date],txwContent.text];
                postStatusText=[[NSString alloc] initWithFormat:@"【保险知识分享】%@,%@,欢迎使用《车E服》(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml)",strInsuranceTitle,txwContent.text];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                                message:[NSString stringWithFormat:@"你将分享以上内容到新浪微博 \"%@\"", postStatusText]
                                                               delegate:self cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:@"OK", nil];
            alertView.tag = 0;
            [alertView show];
            [alertView release];
        }

    }
    else
    {
        [sinaweibo logIn];
    }

}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if (alertView.tag == 0)
        {
            // post status
            NSLog(@"保险知识%@",postStatusText);
            SinaWeibo *sinaweibo = [self sinaweibo];
            [sinaweibo requestWithURL:@"statuses/update.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postStatusText, @"status",
                                       nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if (alertView.tag == 1)
        {
            // post image status
            
            SinaWeibo *sinaweibo = [self sinaweibo];
            
            [sinaweibo requestWithURL:@"statuses/upload.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       postImageStatusText, @"status",
                                       imageDown, @"pic", nil]
                           httpMethod:@"POST"
                             delegate:self];
            
        }
        else if(alertView.tag==2)
        {
            if (isImage==YES && isContent==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = strInsuranceTitle;
                params.paramComment = strInsuranceTitle;
                params.paramSummary =  @"【保险知识分享】,欢迎使用《车E服(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml)";
                //params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                if ([ImgUrl isKindOfClass:[NSString class]]==YES) {
                    if (ImgUrl.length!=0) {
                        params.paramImages=ImgUrl;
                    }
                }
                else
                {
                    [self justShowMessage:@"图片地址无效" title:@"注意"];
                }

                params.paramUrl = @"http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }
            
            if (isContent==YES && isImage==NO) {
                TCAddShareDic *params = [TCAddShareDic dictionary];
                params.paramTitle = strInsuranceTitle;
                params.paramComment =  @"【保险知识分享】,欢迎使用《车E服(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml)";
                params.paramSummary = txwContent.text;
                //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
                
                params.paramUrl = @"http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
                
                if(![_tencentOAuth addShareWithParams:params]){
                    [self showInvalidTokenOrOpenIDMessage];
                }
            }

        }
        else if(alertView.tag==3)
        {
            TCAddShareDic *params = [TCAddShareDic dictionary];
            params.paramTitle =strInsuranceTitle;
            params.paramComment = @"【保险知识分享】,欢迎使用《车E服(http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml)";
            params.paramSummary = txwContent.text;
            //            params.paramImages = @"http://img1.gtimg.com/tech/pics/hv1/95/153/847/55115285.jpg";
            
            params.paramUrl = @"http://www.cpic.com.cn/cx/sz/ydkhd/index.shtml";
            
            if(![_tencentOAuth addShareWithParams:params]){
                [self showInvalidTokenOrOpenIDMessage];
            }
        }
    }
}
- (void)showInvalidTokenOrOpenIDMessage{
    UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
    [alert show];
}
/**
 * Called when the add_share has response.
 */
- (void)addShareResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		[self caculateShareIntegral];
		NSMutableString *str=[NSMutableString stringWithFormat:@""];
		for (id key in response.jsonResponse) {
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:nil
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles:nil];
		[alert show];
        [alert release];
		
		
		
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
        [alert release];
	}
}

-(void)shareQQ
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bKnowledgeInsurance=TRUE;
    
    if([_tencentOAuth isSessionValid])
    {
        if (isImage==YES && isContent==NO) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
        }
        else if(isContent==YES && isImage==NO)
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到腾讯微博" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=3;
            [alert show];
            [alert release];
        }

    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }

}

-(void) ClickCallOutBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setBindCheckRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=62102";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (QQopenId.length!=0) {
        [dicRequest setValue:QQopenId forKey:@"UserId"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"UserId"];
    }
    [dicRequest setValue:@"2" forKey:@"bindingType"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62102" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCheckFail:)];
    [request setDidFinishSelector:@selector(ResonseBindCheckSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseBindCheckSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    NSString *strUserAccount1=[dictResponse objectForKey:@"userAccount"];
    // if ([strResult isEqualToString:@"1"]) {
    if (strUserAccount1.length!=0) {
        //[self justShowMessage:@"登录成功" title:nil];
            bindingQQ=YES;
            [self checkQQAuth];
        }
    else
    {
        //[self justShowMessage:@"登录失败" title:nil];
            bindingQQ=NO;
            [self checkQQAuth];
        
    }

}
-(void)checkQQAuth
{
    if([_tencentOAuth isSessionValid])
    {
        if (bindingQQ==NO) {
            [self justShowMessage:@"你还没绑定本系统账户,请到绑定页面进行绑定" title:@"确定"];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你将分享以上内容到QQ空间" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag=2;
            [alert show];
            [alert release];
        }
    }
    else
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
    
    
}

- (void)ResponseBindCheckFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}
-(void)caculateShareIntegral
{
    RCCaculateIntegral *rcCaculateIntegral=[[RCCaculateIntegral alloc]initCaculateIntegalView];
    [rcCaculateIntegral setCaculatRequest:@"61002"];
    [rcCaculateIntegral setHidden:YES];
    [self.view addSubview:rcCaculateIntegral];
    [rcCaculateIntegral release];
}

- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self justShowMessage:@"授权成功" title:nil];
}
#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" failed!", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    [self caculateShareIntegral];
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
}
- (void)storeAuthQQ
{
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              QQAccessToken, @"QQAccessToken",
                              QQopenId, @"QQopenId", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"Dict_QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - TencentSessionDelegate
/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
	[self justShowMessage:@"QQ登录成功" title:nil];
    
    
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        QQAccessToken = _tencentOAuth.accessToken;
        QQopenId=_tencentOAuth.openId;
        [self storeAuthQQ];
        [self setBindCheckRequest];
    }
    else
    {
        QQAccessToken = @"登录不成功 没有获取accesstoken";
    }
    
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	if (cancelled){
        [self justShowMessage:@"用户取消登录" title:nil];
	}
	else {
        [self justShowMessage:@"登录失败" title:nil];
	}
	
}
/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
    [self justShowMessage:@"无网络连接，请设置网络" title:nil];
}

/**
 * Called when the logout.
 */
-(void)tencentDidLogout
{
    [self justShowMessage:@"退出登录成功，请重新登录" title:nil];
    QQAccessToken = @"";
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [imageContent release];
    [txwContent release];
    [super dealloc];
}

@end
